package com.javafactroy.kunlong.bip.icp.message.test.base;

import io.netty.buffer.*;
import lombok.Data;
import lombok.ToString;
import com.javafactroy.kunlong.bip.icp.message.dxp.iface.IMsgBody;
import com.javafactroy.kunlong.bip.icp.message.dxp.iface.IMsgHeader;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@Data
@ToString
public class TMsgBody implements IMsgBody, Serializable {
    String suiteName;
    String caseName;
    int code;
    String msg;
    String data;

    public TMsgBody() {
        suiteName = "none";
        caseName = "none";
        msg = "";
        data = "";
        code = 200;
    }

    public ByteBuf encode2ByteBuf() {

        ByteBuf byteBuf = Unpooled.buffer(256, IMsgHeader.MAX_FRAME_LENGTH);
        encodeLenString(byteBuf, suiteName);
        encodeLenString(byteBuf, caseName);
        byteBuf.writeInt(code);
        encodeLenString(byteBuf, msg);
        encodeLenString(byteBuf, data);
        return byteBuf;
    }

    void encodeLenString(ByteBuf byteBuf, String value) {
        byteBuf.writeInt(value.length());
        byteBuf.writeBytes(value.getBytes());

    }

    byte[] decodeLenBytes(ByteBuf byteBuf) {
        int l = byteBuf.readInt();
        byte[] bytes = new byte[l];
        byteBuf.readBytes(bytes);
        return bytes;
    }

    String decodeLenString(ByteBuf byteBuf) throws UnsupportedEncodingException {
        return new String(decodeLenBytes(byteBuf), StandardCharsets.UTF_8);
    }

    public void decode(byte[] buf) {
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        byteBuf.writeBytes(buf);
        try {
            suiteName = decodeLenString(byteBuf);
            caseName = decodeLenString(byteBuf);

            code = byteBuf.readInt();
            msg = decodeLenString(byteBuf);
            data = decodeLenString(byteBuf);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

    }


    public void check() {
    //
    }


}
